# -*- encoding=utf8 -*-
__author__ = "GQ"

import random,os,time
import traceback,ctypes
#from airtest.core.api import *
from airtest.cli.parser import cli_setup
from airtest.core.error import DeviceConnectionError
from airtest.core.api import auto_setup,connect_device, device as current_device

device_uri = "Android://127.0.0.1:5037/c9a55ee3?cap_method=ADBCAP&touch_method=MAXTOUCH&"  # 小米9
#device_uri = "android://127.0.0.1:5037/472eedaa?cap_method=ADBCAP&touch_method=MAXTOUCH&"  # oppo R

def check_adb_devices(max_retries=3, retry_interval=2):
    """检查设备连接，支持重试"""
    for attempt in range(max_retries):
        result = os.popen(r"C:\AirtestIDE\airtest\core\android\static\adb\windows\adb.exe devices").read()
        devices = [line for line in result.split("\n") if "\tdevice" in line]
        
        if devices:
            print(f"第 {attempt + 1} 次检测：设备已连接")
            return True
        else:
            print(f"第 {attempt + 1} 次检测：无设备连接，等待 {retry_interval} 秒后重试...")
            time.sleep(retry_interval)
    
    # 如果所有重试都失败，弹窗提示
    ctypes.windll.user32.MessageBoxW(0, "ADB 设备未连接，请检查！", "设备错误", 0x10)
    return False
if not check_adb_devices():
    print("设备连接失败，请检查后重试！")
else:
    print("设备已连接，继续执行...")

if not cli_setup():
    auto_setup(__file__, logdir=True, devices=[device_uri,])
    
# script content
print("start...")
        
for i in range(17):

    if exists(Template(r"tpl1750226498041.png", record_pos=(0.024, -0.202), resolution=(1080, 2340))):
        touch(Template(r"tpl1750226520949.png", record_pos=(0.36, -0.201), resolution=(1080, 2340)))
    sleep(31.0)
    #touch(Template(r"tpl1750226608453.png", record_pos=(-0.194, -0.906), resolution=(1080, 2340)))
    keyevent('back')
    sleep(1.0)


# keyevent("BACK")
